package cn.bluemobi.app.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import cn.bluemobi.app.entity.form.AddressForm;
import cn.bluemobi.app.entity.output.Address;
import cn.bluemobi.app.mapper.AddressMapper;
import cn.bluemobi.app.service.AddressService;
import cn.bluemobi.common.core.dto.Dto;
import cn.bluemobi.common.core.dto.ListDto;

/**
 * 
 * @author lvxh
 * 
 */
@Service
@Transactional
public class AddressServiceImpl implements AddressService {

	@Autowired
	private AddressMapper addressMapper;

	@Override
	public ListDto<Address> findAllAddress(String memberId) {
		ListDto<Address> dto = new ListDto<>();
		List<Address> addresses = addressMapper.findAddressByMemberId(memberId);
		dto.setList(addresses);
		return dto;
	}

	@Override
	public Dto<Object> saveOrUpdateAddress(String memberId,
			AddressForm addressForm) {
		addressForm.setMemberId(memberId);
		if (StringUtils.isEmpty(addressForm.getId())) {
			addressMapper.insertAddress(addressForm);
		} else {
			addressMapper.updateAddress(addressForm);
		}
		// 只能有一个默认地址
		if (StringUtils.equals(addressForm.getIsDefault(), "1")) {
			addressMapper.updateAddressNotDefault(addressForm.getMemberId(),
					addressForm.getId());
		}
		return Dto.SUCCESS;
	}

	@Override
	public Dto<Object> deleteAddress(String memberId, String addressId) {
		addressMapper.deleteAddress(addressId);
		Address address = addressMapper.findDefaultAddress(memberId);
		if (address == null) {
			List<Address> addresses = addressMapper
					.findAddressByMemberId(memberId);
			if (!CollectionUtils.isEmpty(addresses)) {
				addressMapper.updateDefaultAddress("1", addresses.get(0)
						.getAddressId());
			}
		}
		return Dto.SUCCESS;
	}

	@Override
	public Dto<Address> findDefaultAddress(String memberId) {
		Dto<Address> dto = new Dto<Address>();
		Address address = addressMapper.findDefaultAddress(memberId);
		dto.setData(address);
		return dto;
	}
}
